package com.school.hjt.schoolclasscard.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.google.gson.Gson;
import com.school.hjt.schoolclasscard.BaseApplication;
import com.school.hjt.schoolclasscard.IMyAidlInterface;
import com.school.hjt.schoolclasscard.bean.API;
import com.school.hjt.schoolclasscard.bean.HomeBean;
import com.school.hjt.schoolclasscard.db.AddData;
import com.school.hjt.schoolclasscard.db.Album;
import com.school.hjt.schoolclasscard.db.CardDao;
import com.school.hjt.schoolclasscard.db.CardStudent;
import com.school.hjt.schoolclasscard.db.ClassAlbum;
import com.school.hjt.schoolclasscard.db.ClassInfo;
import com.school.hjt.schoolclasscard.db.DynamicSchool;
import com.school.hjt.schoolclasscard.db.Labours;
import com.school.hjt.schoolclasscard.db.SchAboutUs;
import com.school.hjt.schoolclasscard.db.SchArticle;
import com.school.hjt.schoolclasscard.db.SchInfo;
import com.school.hjt.schoolclasscard.db.StudentSign;
import com.school.hjt.schoolclasscard.utlis.APPUtlis;
import com.school.hjt.schoolclasscard.utlis.ClassCalendar;
import com.school.hjt.schoolclasscard.utlis.Constant;
import com.school.hjt.schoolclasscard.utlis.DownLoadImageService;
import com.school.hjt.schoolclasscard.utlis.ImageDownLoadCallBack;
import com.school.hjt.schoolclasscard.utlis.OkhttPost;
import com.school.hjt.schoolclasscard.utlis.PrefUtild;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;

/**
 * Created by xqx on 2017/11/10.
 * 更新服务
 */
public class LocalService extends Service  {
    private ServiceConnection conn;
    private MyService myService;
    Intent intent = new Intent();
    List<String> studentList=new ArrayList<>();//删除学生
    List<String> AlbumId=new ArrayList<>();//删除相册
    List<String> AlbumClassId=new ArrayList<>();//删除动态
    List<String> ArtSchoolId=new ArrayList<>();//删除动态
    List<String> Sch_article=new ArrayList<>();//删除值日生
    List<String> Sch_AboutUs=new ArrayList<>();//删除值日生
    List<String> LabourId=new ArrayList<>();//删除值日生
    AddData addData=new AddData();
    @Override
    public IBinder onBind(Intent intent) {
        return myService;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        init();
//        AlarmManager();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run(){
                OkhttPost.Okget(API.HOME+ Constant.SNO,1,new ServiceClaa());
            }
        },10000,12000);
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run(){
//                OkhttPost.Okget(API.KAOQIN+ Constant.SNO,2,new ServiceClaa());
//            }
//        },8000,3000);
    }
    /**
     //     * 单线程列队执行
     //     */
    private static ExecutorService singleExecutor = null;
    /**
     * 执行单线程列队执行
     */
    public void runOnQueue(Runnable runnable) {
        if (singleExecutor == null) {
            singleExecutor = Executors.newSingleThreadExecutor();
        }
        singleExecutor.submit(runnable);
    }

    /**
     * 启动图片下载线程
     */
    private void onDownLoad(final String url, final String type) {
        DownLoadImageService service = new DownLoadImageService(getApplicationContext(),
                url,
                new ImageDownLoadCallBack() {

                    @Override
                    public void onDownLoadSuccess(File file) {
                        // 在这里执行图片保存方法
                        APPUtlis.copyFile(file.getAbsolutePath(), Environment.getExternalStorageDirectory().getPath() + "/Face/"+APPUtlis.getMd5Value(url)+".hjt");
                        if (type.equals("1")){
                            intent.setAction(Constant.BANNER);
                            sendBroadcast(intent);
                        }else{
                            intent.setAction(Constant.RONGYU);
                            sendBroadcast(intent);
                        }
                    }
                    @Override
                    public void onDownLoadFailed() {
                        // 图片保存失败
                    }
                });
        //启动图片下载线程
        runOnQueue(service);
    }
    private void init() {
        if (conn == null) {
            conn = new MyServiceConnection();
        }
        myService = new MyService();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intents = new Intent();
        intents.setClass(this, RemoteService.class);
        bindService(intents, conn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }



    class MyService extends IMyAidlInterface.Stub {
        @Override
        public String getName() throws RemoteException {
            return null;
        }
    }

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LocalService.this.startService(new Intent(LocalService.this,
                    RemoteService.class));
            LocalService.this.bindService(new Intent(LocalService.this,
                    RemoteService.class), conn, Context.BIND_IMPORTANT);
        }

    }
    public void AlarmManager(){
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime = System.currentTimeMillis();
        Intent intent = new Intent();
//        intent.setAction(Constant.TO);
        sendBroadcast(intent);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
        manager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime,AlarmManager.INTERVAL_HALF_HOUR , pi);
//        manager.set(AlarmManager.RTC_WAKEUP,triggerAtTime,pi);
    }
    class ServiceClaa implements OkhttPost.Callback{
        @Override
        public void onError(Call call, Exception e, int id) {
            intent.setAction(Constant.ERR);
            intent.putExtra(Constant.ERR, ClassCalendar.getIntDay()+": 主页数据接口访问失败"+e.toString());
            sendBroadcast(intent);
            if (id==2){
                Log.e("ATG","考勤报错 "+e.toString());
            }
        }
        @Override
        public void onResponse(String response, int id) {
            Gson gson = new Gson();
            try {
                if (id==1){
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 主页接口访问成功");
                    sendBroadcast(intent);
                    HomeBean homeBean = gson.fromJson(response, HomeBean.class);
                    if (homeBean.code==1){
                        HomeBean.Sch_board sch_board = homeBean.sch_board;
                        List<SchInfo> schInfos = CardDao.querySchInfoId(sch_board.id);
                        Log.e("ATG","1");
                        if (schInfos.size()!=0){
                            if (!schInfos.get(0).getSchool_name().equals(sch_board.school_name)||!schInfos.get(0).getMotto().equals(sch_board.motto==null?"暂无校训":sch_board.motto)||
                                    !schInfos.get(0).getSchool_img().equals(sch_board.school_img)){
                                addData.addInfo(sch_board.id,sch_board.school_name,sch_board.school_img,sch_board.motto==null?"暂无校训":sch_board.motto);
                                intent.setAction(Constant.INFO);
                                sendBroadcast(intent);
                                intent.setAction(Constant.SCHNAME);
                                sendBroadcast(intent);
                            }
                        }else{
                                addData.addInfo(sch_board.id,sch_board.school_name,sch_board.school_img,sch_board.motto==null?"暂无校训":sch_board.motto);
                                intent.setAction(Constant.INFO);
                                sendBroadcast(intent);
                                intent.setAction(Constant.SCHNAME);
                                sendBroadcast(intent);
                        }
                        List<HomeBean.Class_info> class_infos = homeBean.class_info;
                        List<ClassInfo> classInfos = CardDao.queryClassInfo();
                        if (class_infos!=null){
                            for (HomeBean.Class_info class_info:class_infos){
                                String motto = class_info.class_motto == null ? "暂无班训" : class_info.class_motto;
                                if (classInfos.size()!=0){
                                    if (!motto.equals(classInfos.get(0).class_motto)){
                                        addData.addClassInfo(motto);
                                        intent.setAction(Constant.LABOUR);
                                        sendBroadcast(intent);
                                    }
                                }else{
                                        addData.addClassInfo(motto);
                                        intent.setAction(Constant.LABOUR);
                                        sendBroadcast(intent);
                                }
                            }
                        }
                        ArtSchoolId.clear();
                        List<HomeBean.Art_school> art_schools = homeBean.art_school;
                        for (HomeBean.Art_school art_school:art_schools){
                            ArtSchoolId.add(art_school.id);
                            List<DynamicSchool> dynamicSchools = CardDao.queryDynamicSchoolId(art_school.id);
                            if (dynamicSchools.size()!=0){
                                if (!dynamicSchools.get(0).add_time.equals(art_school.add_time)){
                                    addData.addDynamicSchool(art_school.id,art_school.content,art_school.add_time);
                                    intent.setAction(Constant.ARTSCHOOL);
                                    sendBroadcast(intent);
                                }
                            }else{
                                    addData.addDynamicSchool(art_school.id,art_school.content,art_school.add_time);
                                    intent.setAction(Constant.ARTSCHOOL);
                                    sendBroadcast(intent);
                            }
                        }
                        AlbumId.clear();
                        List<HomeBean.Album> album = homeBean.album;
                        for (int i=0;i<album.size();i++){
                            AlbumId.add(album.get(i).id);
                            List<ClassAlbum> classAlba = CardDao.queryAlbumId(album.get(i).id);
                            if (classAlba.size()!=0){
                                String str = album.get(i).title == null ? "无标题" : album.get(i).title;
                                if (!classAlba.get(0).getTitle().equals(str)){
                                    addData.addAlbum(album.get(i).id,album.get(i).add_time,album.get(i).pic_path,album.get(i).type_id,album.get(i).title==null?"无标题":album.get(i).title);
                                    if (album.get(i).type_id.equals("1")){
                                        intent.setAction(Constant.BANNER);
                                        sendBroadcast(intent);
                                    }else if(album.get(i).type_id.equals("3")){
                                        intent.setAction(Constant.ALBUM);
                                        sendBroadcast(intent);
                                    }else {
                                        intent.setAction(Constant.RONGYU);
                                        sendBroadcast(intent);
                                    }
                                }
                            }else{
                                    addData.addAlbum(album.get(i).id,album.get(i).add_time,album.get(i).pic_path,album.get(i).type_id,album.get(i).title==null?"无标题":album.get(i).title);
                                if (album.get(i).type_id.equals("3")){
                                    intent.setAction(Constant.ALBUM);
                                    sendBroadcast(intent);
                                }
                                    onDownLoad(album.get(i).pic_path,album.get(i).type_id);
                            }
                        }
                        List<HomeBean.Class_album> class_album = homeBean.class_album;
                        AlbumClassId.clear();
                        if (class_album!=null){
                            for (HomeBean.Class_album album1:class_album){
                                AlbumClassId.add(album1.id);
                                List<Album> alba = CardDao.queryClassAlbumId(album1.id);
                                if (alba.size()==0){
//                                Log.e("ATG","123");
                                    addData.addClassAlbum(album1.id,album1.pic_path,album1.add_time);
                                    intent.setAction(Constant.LABOUR);
                                    sendBroadcast(intent);
                                }
                            }
                        }
                        studentList.clear();
                        if (Constant.isTS){
                            List<HomeBean.Student> students = homeBean.student;
                            for (int i=0;i<students.size();i++){
                                studentList.add(students.get(i).student_no);
                                if (students.get(i).card_no!=null) {
                                    String headimg="";
                                    if (students.get(i).headimg!=null){
                                        headimg=students.get(i).headimg;
                                    }
                                    List<CardStudent> cardStudents = CardDao.queryStudentId(students.get(i).student_no);
                                    if (cardStudents.size()!=0){
                                        if (!cardStudents.get(0).getCard_no().equals(students.get(i).card_no)||!cardStudents.get(0).getStudent_name().equals(students.get(i).name)
                                                || !cardStudents.get(0).getStudent_url().equals(headimg)){
//                                        Log.e("ATG","进来学生");
                                            addData.addStudent(students.get(i).student_no,students.get(i).card_no,students.get(i).name,headimg);
                                            intent.setAction(Constant.KQ);
                                            sendBroadcast(intent);
                                        }
                                    }else{
//                                        Log.e("ATG","进来学生1"+students.get(i).name);
                                        addData.addStudent(students.get(i).student_no,students.get(i).card_no,students.get(i).name,headimg);
                                        intent.setAction(Constant.KQ);
                                        sendBroadcast(intent);
                                    }
                                }
                            }
                        }else{
                            List<HomeBean.Teacher> students = homeBean.teacher;
                            for (int i=0;i<students.size();i++){
                                studentList.add(students.get(i).teacher_no);
                                if (students.get(i).card_no!=null) {
                                    String headimg="";
                                    if (students.get(i).headimg!=null){
                                        headimg=students.get(i).headimg;
                                    }
                                    List<CardStudent> cardStudents = CardDao.queryStudentId(students.get(i).teacher_no);
                                    if (cardStudents.size()!=0){
                                        if (!cardStudents.get(0).getCard_no().equals(students.get(i).card_no)||!cardStudents.get(0).getStudent_name().equals(students.get(i).teacher_name)
                                                || !cardStudents.get(0).getStudent_url().equals(headimg)){
//                                            Log.e("ATG","进来学生");
                                            addData.addStudent(students.get(i).teacher_no,students.get(i).card_no,students.get(i).teacher_name,headimg);
                                            intent.setAction(Constant.KQ);
                                            sendBroadcast(intent);
                                        }
                                    }else{
                                            addData.addStudent(students.get(i).teacher_no,students.get(i).card_no,students.get(i).teacher_name,headimg);
                                            intent.setAction(Constant.KQ);
                                            sendBroadcast(intent);
                                    }
                                }
                            }
                        }
                        List<HomeBean.Sch_article> sch_article = homeBean.sch_article;
                        Sch_article.clear();
                        for (int i=0;i<sch_article.size();i++){
                            Sch_article.add(sch_article.get(i).id);
                            List<SchArticle> schArticles = CardDao.querySchArticle(sch_article.get(i).id);
                            if (schArticles.size()!=0){
                                if (!schArticles.get(0).add_time.equals(sch_article.get(i).add_time)){
                                    addData.addSchArtcle(sch_article.get(i).id,sch_article.get(i).title,sch_article.get(i).sort,
                                            sch_article.get(i).image_path,sch_article.get(i).content,sch_article.get(i).link,sch_article.get(i).add_time);
                                    intent.setAction(Constant.ARTICLR);
                                    sendBroadcast(intent);
                                }
                            }else{
                                    addData.addSchArtcle(sch_article.get(i).id,sch_article.get(i).title,sch_article.get(i).sort,
                                            sch_article.get(i).image_path,sch_article.get(i).content,sch_article.get(i).link,sch_article.get(i).add_time);
                                    intent.setAction(Constant.ARTICLR);
                                    sendBroadcast(intent);
                            }
                        }
                        List<HomeBean.About_us> about_us = homeBean.about_us;
                        Sch_AboutUs.clear();
                        for (int i=0;i<about_us.size();i++){
                            Sch_AboutUs.add(about_us.get(i).id);
                            List<SchAboutUs> schAboutUses = CardDao.querySchAboutUs(about_us.get(i).id);
                            if (schAboutUses.size()!=0){
                                if (!schAboutUses.get(0).add_time.equals(about_us.get(i).add_time)){
                                    addData.addSchAboutUs(about_us.get(i).id,about_us.get(i).title,about_us.get(i).sort,about_us.get(i).type_id,about_us.get(i).
                                            content,about_us.get(i).link,about_us.get(i).add_time);
                                    intent.setAction(Constant.JIANJIE);
                                    sendBroadcast(intent);
                                }
                            }else{
                                    addData.addSchAboutUs(about_us.get(i).id,about_us.get(i).title,about_us.get(i).sort,about_us.get(i).type_id,about_us.get(i).
                                        content,about_us.get(i).link,about_us.get(i).add_time);
                                intent.setAction(Constant.JIANJIE);
                                sendBroadcast(intent);
                            }
                        }
                        List<HomeBean.Labour> labours = homeBean.labour;
                        LabourId.clear();
                        for (HomeBean.Labour labour:labours){
                            String replace = labour.now_date.replace("-", "");
                            LabourId.add(labour.id+replace);
                            String str="";
                            String str1="";
                            List<Labours> labourses = CardDao.queryLaboursId(labour.id+replace);
                            List<HomeBean.Lab_teacher> lab_teachers = labour.lab_teacher;
                            List<HomeBean.Adm_teacher> adm_teachers = labour.adm_teacher;
                            if (lab_teachers!=null){
                                for (HomeBean.Lab_teacher lab_teacher:lab_teachers){
                                    str+=lab_teacher.teacher_name+" ";
                                }
                            }else{
                                str="暂无";
                            }
                            if (adm_teachers!=null){
                                for (HomeBean.Adm_teacher adm_teacher:adm_teachers){
                                    str1+=adm_teacher.teacher_name+" ";
                                }
                            }else{
                                str1="暂无";
                            }
                            if (labourses.size()!=0){
                                if (!labourses.get(0).getAdd_time().equals(labour.add_time)||!labourses.get(0).getClassname().equals(labour.classname)
                                        ||!labourses.get(0).getWeek_day().equals(labour.week_day)){
                                    addData.addLabours(labour.id+replace,labour.week_day,labour.classname,labour.now_date,labour.add_time,str,str1);
                                    intent.setAction(Constant.LABOUR);
                                    sendBroadcast(intent);
                                }
                            }else {
//                                    Log.e("ATG","进来值日12");
                                    addData.addLabours(labour.id+replace,labour.week_day,labour.classname,labour.now_date,labour.add_time,str,str1);
                                    intent.setAction(Constant.LABOUR);
                                    sendBroadcast(intent);
                            }
                        }
                        //删除值日
                        List<Labours> labourses = CardDao.queryLabours();
                        for (Labours labours1:labourses){
                            boolean contains = LabourId.contains(labours1.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getLaboursDao().deleteByKey(labours1.getId());
                                BaseApplication.getDaoInstant().clear();
                                intent.setAction(Constant.LABOUR);
                                sendBroadcast(intent);
                            }
                        }
                        //删除校园公告
                        List<DynamicSchool> dynamics = CardDao.queryDynamicSchool();
                        for (DynamicSchool dynami1:dynamics){
                            boolean contains = ArtSchoolId.contains(dynami1.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getDynamicSchoolDao().deleteByKey(dynami1.getId());
                                BaseApplication.getDaoInstant().clear();
                                intent.setAction(Constant.ARTSCHOOL);
                                sendBroadcast(intent);
                            }
                        }
                        //删除简介
                        List<SchAboutUs> schAboutUs = CardDao.querySchAboutUs();
                        for (SchAboutUs aboutUs:schAboutUs){
                            boolean contains = Sch_AboutUs.contains(aboutUs.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getSchAboutUsDao().deleteByKey(aboutUs.getId());
                                BaseApplication.getDaoInstant().clear();
//                                Log.e("ATG","3   3");
                                intent.setAction(Constant.JIANJIE);
                                sendBroadcast(intent);
                            }
                        }
                        //删除资讯
                        List<SchArticle> schArticles = CardDao.querySchArticle();
                        for (SchArticle schArticle:schArticles){
                            boolean contains = Sch_article.contains(schArticle.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getSchArticleDao().deleteByKey(schArticle.getId());
                                BaseApplication.getDaoInstant().clear();
                                intent.setAction(Constant.ARTICLR);
                                sendBroadcast(intent);
                            }
                        }
                        //删除学生
                        List<CardStudent> cardStudents = CardDao.queryStudent();
                        for (CardStudent student:cardStudents){
                            boolean contains = studentList.contains(student.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getCardStudentDao().deleteByKey(student.getId());
                                BaseApplication.getDaoInstant().clear();
                            }
                        }
                        //删除相册
                        List<ClassAlbum> classAlba = CardDao.queryAlbum();
                        for (ClassAlbum album1:classAlba){
                            boolean contains = AlbumId.contains(album1.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getClassAlbumDao().deleteByKey(album1.getId());
                                BaseApplication.getDaoInstant().clear();
                                Log.e("ATG","执行删除");
                                File file=new File(Environment.getExternalStorageDirectory().getPath() + "/Face/"+APPUtlis.getMd5Value(album1.getPic())+".hjt");
                                file.delete();
                                if (album1.getTypeid().equals("2")){
                                    intent.setAction(Constant.RONGYU);
                                    sendBroadcast(intent);
                                }else if (album1.getTypeid().equals("3")){
                                    intent.setAction(Constant.ALBUM);
                                    sendBroadcast(intent);
                                }else{
                                    intent.setAction(Constant.BANNER);
                                    sendBroadcast(intent);
                                }
                            }
                        }
                        //删除相册
                        List<Album> Alba = CardDao.queryAlbum1();
                        for (Album album1:Alba){
                            boolean contains = AlbumClassId.contains(album1.getId());
                            if (!contains){
                                BaseApplication.getDaoInstant().getAlbumDao().deleteByKey(album1.getId());
                                BaseApplication.getDaoInstant().clear();
                                intent.setAction(Constant.LABOUR);
                                sendBroadcast(intent);
                            }
                        }
                    }
                }else if(id==2){
                    Log.e("ATG","考勤"+response);
                    String num = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.NUM, "0");
//                    Log.e("ATG","数量 "+num);
                    assert num != null;
                    if (!num.equals(response)){
                        PrefUtild.INSTANCE.setString(getApplicationContext(),Constant.NUM,response);
                        intent.setAction(Constant.KQ);
                        sendBroadcast(intent);
                    }
                }
            }catch (Exception e){
                Log.e("ATG","主页接口"+e.toString());
                intent.setAction(Constant.ERR);
                intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 接口解析错误"+e.toString());
                sendBroadcast(intent);
            }
        }
    }
}